<template>
  <div class="userMain">
    <h3>用户列表组件</h3>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>卡片名称</span>
        <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
      </div>
      <!-- 搜索与添加区域 -->

      <el-row :gutter="22">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button slot="append" @click="getUserList" icon="el-icon-search">搜索</el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="onAddDialog" type="success">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="编号" width="60"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="id" label="编号" width="150"></el-table-column>
        <el-table-column prop="create_time" label="创建日期"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <!-- boolean值无法直接渲染 -->
        <el-table-column label="状态">
          <!-- 同时指定了prop和定义作用域插槽template 那么prop失效 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
              active-text="开"
              inactive-text="关"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350px">
          <template slot-scope="scope">
            <!-- <el-link type="info">{{scope.row.id}}</el-link> -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            >删除</el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <!-- layout是用来指定页面上显示哪些布局结构的 -->
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="新建用户界面" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体区域 -->

      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        :model="editFormData"
        :rules="addFormRules"
        ref="editFormDataRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="editFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="id" prop="id">
          <el-input disabled v-model="editFormData.id"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色的对话框"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 行为区
export default {
  data () {
    // 定义校验规则
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      // const regEmail = /^\w+@\w+(\.\w+)+$/
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入正确邮箱地址！'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1, // 当前的页数 current
        pagesize: 2 // 当前每页显示多少条数据
      },
      userList: [],
      total: null,
      flag: false,
      addDialogVisible: false,
      editDialogVisible: false,
      // 查询时存储获取到的表单数据对象
      editFormData: {},

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''

      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入电话', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }]
      },
      // 分配权限对话框打开或关闭
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色的ID
      selectedRoleId: []
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        // get参数
        params: this.queryInfo
      })
      // console.log('用户列表数据__>', res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userList = res.data.users
      this.total = res.data.total
      this.flag = res.data.users.mg_state
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码 值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch 状态的改变
    async userStateChanged (e) {
      console.log(e.mg_state, e)
      const { data: res } = await this.$http.put(`users/${e.id}/state/${e.mg_state}`)
      if (res.meta.status !== 200) {
        e.mg_state = !e.mg_state
        return this.$message.error('修改用户状态失败！')
      } else {
        this.$message.success('修改用户状态成功！')
      }
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    // 打开新建对话框
    onAddDialog () {
      this.addDialogVisible = true
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮，添加新用户
    addUser () {
      // this.$refs.addFormRef.validate(valid => { console.log(valid) })
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败！')
          }
          this.$message.success('添加用户成功！')
          // 添加成功之后隐藏对话框
          this.addDialogVisible = false
          // 重新获取用户列表数据
          this.getUserList()
        } else {
          return false
        }
      })
    },
    // 展示编辑对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败！')
      this.editFormData = res.data
      console.log('准备修改', id, res)

      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormDataRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormDataRef.validate(async valid => {
        console.log(valid)
        if (!valid) return false
        // 发起修改用户信息的数据请求
        else {
          const { data: res } = await this.$http.put('users/' + this.editFormData.id, {
            email: this.editFormData.email, mobile: this.editFormData.mobile
          })
          if (res.meta.status !== 200) {
            this.$message.error('修改用户信息失败！')
          }
          this.$message.success('修改用户信息成功！')
          // 添加成功之后隐藏对话框
          this.editDialogVisible = false
          // 重新获取用户列表数据
          this.getUserList()
        }
      })
    },
    // 根据ID删除用户的对应信息
    async removeUserById (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 调用接口删除指定ID项
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          this.$message.error('删除用户信息失败！')
        }
      }).then(() => {
        // 提示删除成功
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).then(() => {
        // 重新获取列表
        this.getUserList()
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示分配角色的对话框
    async setRole (userInfo) {
      console.log('当前用户信息', userInfo)
      this.userInfo = userInfo
      // 在展示对话框之前获取所有的角色的列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data

      this.setRoleDialogVisible = true
    },
    // 点击按钮分配权限
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('分配角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 更新分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }

  }

}
</script>

<style lang="less" scope>
.userMain {
  background-color: #eaedf1;
}
</style>
